package com.offcn.file.controller;

import com.offcn.common.entity.Result;
import com.offcn.common.entity.StatusCode;
import com.offcn.file.util.FastDFSClient;
import org.apache.tomcat.jni.Multicast;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件上传
 *
 * @author 30389
 * @date 2022/10/13 15:30:01
 */
@RestController
@RequestMapping("file")
public class fileController {

    @Value("${FILE_SERVER_URL}")
    private String path;

    @PostMapping("upload")
    public Result upload(MultipartFile file) {
        try {
            if (file != null && !file.isEmpty()) {
                String originalFilename = file.getOriginalFilename();
                //获取“.”的位置
                int index = originalFilename.lastIndexOf(".");
                //截取“.”后面的字符串
                String substring = originalFilename.substring(index + 1);

                FastDFSClient fastDFSClient = new FastDFSClient("classpath:fdfs_client.conf");
                String id = fastDFSClient.uploadFile(file.getBytes(), substring);
                return new Result<>(true, StatusCode.OK, "上传成功", path + id);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result<>(false, StatusCode.ERROR, "上传失败");
    }
}
